package com.wesh.uaa.config;

import com.wesh.uaa.config.handler.ClientAccessDeniedHandler;
import com.wesh.uaa.config.providers.UsernamePasswordAuthenticationProvider;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.HttpMethod;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.ProviderManager;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;

import javax.annotation.Resource;
import java.util.Arrays;

/**
 * Security web 全局配置
 */
@Configuration
@EnableGlobalMethodSecurity(securedEnabled = true, prePostEnabled = true)
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {

    @Resource
    ClientAccessDeniedHandler clientAccessDeniedHandler;

    /**
     * 用户名密码验证 提供操作
     */
    @Autowired
    UsernamePasswordAuthenticationProvider usernamePasswordAuthenticationProvider;

    /**
     * 配置 Http 请求 安全策略
     * @param http
     * @throws Exception
     */
    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.csrf().disable()  //关闭 csrf 保护
                .authorizeRequests().antMatchers(HttpMethod.OPTIONS,"/login","/oauth/**").permitAll() //配置哪些路径可以访问
                .anyRequest().authenticated() //配置所有的请求都要权限验证
                .and()
                .formLogin()
                //.loginPage("/login.html") //自定义登录页面
                .and()
                .exceptionHandling().accessDeniedHandler(clientAccessDeniedHandler); //配置访问受限时的情况
        //super.configure(http);
    }

    /**
     * 配置一个 provider 进行用户信息的获取和验证操作
     * @param auth
     * @throws Exception
     */
    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth.authenticationProvider(usernamePasswordAuthenticationProvider);
    }

    /**
     * 初始化一个 provider 提供校验操作
     * @return
     * @throws Exception
     */
    @Bean
    public AuthenticationManager authenticationManager() throws Exception {
        return new ProviderManager(usernamePasswordAuthenticationProvider);
    }

    /**
     * 设置密码加密方式
     * @return
     */
    @Bean
    public PasswordEncoder passwordEncoder(){
        return new BCryptPasswordEncoder();
    }
}
